<template>
  <div>
    <div id="container" class="mapspec">
      <el-form ref="form" :inline="true" :model="form" label-width="80px" style="position:absolute;top:1px;z-index: 100;width: 100%;">
        <el-row>
          <el-col :span="20">
            <el-form-item label="">
              <el-select v-model="form.fqs" multiple placeholder="选择时间点">
                <el-option v-for="item in timeList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="type" placeholder="选择类型">
                <el-option v-for="item in typeList" :key="item.name" :label="item.name" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 右侧数值展示 -->
      <div class="pmsz" v-if="pmVal">
        <div class="title">PM2.5: </div>
        <div>{{ pmVal }}</div>
      </div>
      <div class="zbzs">
        <header>
          <div class="titleBox">
            <img class="icon" src="@/images/bigscreen/zzb.png" alt="" srcset="">
            <div class="title">详细指标</div>
          </div>
          <img class="select-icon" :src="require('@/images/bigscreen/' + iconType + '.png')" alt="" srcset="" @click="changeSelect">
        </header>
        <div class="content" v-show="iconType == 'open'">
          <el-scrollbar style="height:100%">
            <div class="row" :class="{ active: item.id == activeAddressId }" v-for="item in rightDataList" :key="item.id" @click="chooseAddress(item)">
              <div class="header">
                <img class="icon" src="@/images/bigscreen/address.png" alt="" srcset="">
                <div class="title">{{ item.areaPoint.pointName }}</div>
              </div>
              <div class="data-info">
                <div class="info-item">
                  <div class="name">PM2.5</div>
                  <div class="progressBox">
                    <div class="progress" :style="{ width: parseFloat((item.calPm2 * 100) / maxByPM2).toFixed(2) + 'px'}"></div>
                  </div>
                  <div class="value">{{ (item.calPm2).toFixed(2) }}</div>
                </div>
                <div class="info-item">
                  <div class="name">NO2</div>
                  <div class="progressBox">
                    <div class="progress NO2" :style="{ width: parseFloat((item.calNo2 * 100) / maxByNo2).toFixed(2) + 'px'}"></div>
                  </div>
                  <div class="value">{{ (item.calNo2).toFixed(2) }}</div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script src="https://a.amap.com/jsapi_demos/static/resource/heatmapData.js"></script>
<script src="https://a.amap.com/Loca/static/mock/wjarea.js"></script>
<script>

import AMapLoader from '@amap/amap-jsapi-loader';
import { listPoint } from "@/api/wrj/point";
import { getTimeList, listInfo,listForMultiple, getPlanePostion } from "@/api/wrj/info";
import { multipleTaskForHotmap } from "@/api/wrj/djPath";

export default {
  name: "map-view",
  data() {
    return {
      // 街道区块矩形数组对象,只有虚线，没有底色，
      polygonArr: [],
      // pm2.5区块矩形数组对象，有颜色，
      pmPolygonArr:[],
      textArr:[],
      queryParams:{
        pageNum:1,
        pageSize:99999
      },
      textFontSize:10,
      timer:null,
      loca: undefined,
      form: {
        fqs:[],
        fq:"",// 时间分区
        rq:"",//日期
        hour:"",// 时间点
        jd:"北海",//街道
        pageNum:1,
        pageSize:99999
      },
      queryParams:{
        pageNum:1,
        pageSize:99999,
        jd:"北海",//街道
      },
      timeList: [],
      isTasking: false, // 任务是否结束
      heatmapData:[],   // 热力图数据
      heatmap:null,     // 热力图插件对象
      pathData:[],      // 飞行轨迹数据
      polyline:null,     // 飞行轨迹线对象
      markerList: [],
      typeList: [
        { name: 'PM2.5', value: 'PM2.5(ug/m3)' },
        { name: 'NO2', value: 'NO2(ppm)' }
      ],
      type: 'PM2.5(ug/m3)',
      heatmapMaxData:100,
      iconType: 'close', // 展示下拉或收起
      rightDataList: [], // 右侧列表数据
      maxByPM2: null,
      maxByNo2: null,
      activeAddressId: '',
      contourLayer:null,// 等值面对象
      layer:null,
      planeArr: [],
      pmVal: ''
    }
  },
  mounted() {
    this.getTimeList();
    this.$nextTick(()=>{
      this.initAMap();
    })
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    // 修改下拉样式
    changeSelect() {
      if(this.iconType == 'close') {
        this.iconType = 'open';
      } else {
        this.iconType = 'close';
      }
    },
    // 选择小区
    chooseAddress(row) {
      this.activeAddressId = row.id;
      this.map.remove(this.textArr);
      this.textArr=[];
      this.map.setCenter(new AMap.LngLat(JSON.parse(row.areaPoint.centerpoint).lng, JSON.parse(row.areaPoint.centerpoint).lat));

      var text = new AMap.Text({
        text: `
          <div class="custom-label">
            <div class="label-text">${row.areaPoint.pointName}</div>
            <div class="label-text">PM2.5: ${row.calPm2.toFixed(2)}</div>
            <div class="label-text">NO2: ${row.calNo2.toFixed(2)}</div>
          </div>
        `,  // 文本内容
        position: [JSON.parse(row.areaPoint.centerpoint).lng, JSON.parse(row.areaPoint.centerpoint).lat], // 坐标
        style: {
          fontSize: "16px",
          // color: "#FF0000",
          backgroundColor: "rgba(255,255,255,0)",
          border: "1px solid rgba(255,255,255,0)",
          padding: "0px",
          // cursor: "pointer",        // 鼠标悬停样式
        },
        map: this.map                   // 绑定到地图
      });
      this.textArr.push(text);
    },
    // 根据街道，获取pm任务分区时间列表
    getTimeList(){
      getTimeList(this.form).then(response => {
        var data = response.rows;
        if(data!=null){
          data.forEach(item=>{
            this.timeList.push(item.fq)
          })
        }
      });
    }, 
    // 查询pm2.5数据
    onSubmit(){
      console.log(this.form)
      this.iconType = "open";
      this.map.remove(this.textArr);
      this.textArr=[];
      this.getInfoListForRight();

      this.getHotmapAndDjPath();

      this.map.setCenter(new AMap.LngLat(120.553599,29.998892));
    },
    // 获取飞机定位信息
    getPlanePostion(){
      getPlanePostion(this.form).then(response => {
        let data = response.data;
        console.log('111', response.data)
        if(data!=null){
          this.pmVal = data.airData[this.type];
          this.map.remove(this.planeArr);
          this.planeArr=[];
          var marker = new AMap.Marker({
            icon: new AMap.Icon({
              image: require('@/images/bigscreen/wrj.png'),  // 图标URL
              size: new AMap.Size(30, 15),  // 图标大小
              imageSize: new AMap.Size(30, 15)  // 图片实际大小
            }),
            position: [data.longitude, data.latitude],
          });
          this.planeArr.push(marker) ;
          
          if(this.planeArr.length>0){
            this.map.add(this.planeArr);
          }
        } else {
          clearInterval(this.timer);
        }
        
      });
    },
    // 根据街道和任务，获取飞行轨迹以及热力图的数据
    getHotmapAndDjPath(){
      this.form.fq = this.form.fqs.join(',');
      multipleTaskForHotmap(this.form).then(response => {
        // 画热力图
        if(response.data) {

        
        console.log(response.data)
        var data = response.data;
        var that = this;
        this.heatmapData = [];
        this.pathData = [];
        let maxdata = 0;


        var districtData =[];
        console.log('this.contourLayer', this.contourLayer)
        if(this.contourLayer) {
          this.contourLayer.setData(districtData, {
          // lnglat: {string}, 数据中经纬度坐标所在的列名称, 必填
          lnglat: 'lnglat',
          // value: {string}, 数据中权重数据所在的列名称, 必填
          value: 'count'
        });
        }
        
        
        data.forEach(item=>{

        districtData.push({
          "lng": item.lng,
          "lat": item.lat,
          // "count":30,
          "count": item.messageInfo.airData[this.type],
          "lnglat": item.lng+","+item.lat
        })
        });


        // 设置等高线依赖的数据
        // districtData: 绘制等高线时依赖的用户数据
        this.contourLayer.setData(districtData, {
          // lnglat: {string}, 数据中经纬度坐标所在的列名称, 必填
          lnglat: 'lnglat',
          // value: {string}, 数据中权重数据所在的列名称, 必填
          value: 'count'
        });
        // 设置等高线属性值
        this.contourLayer.setOptions({
            // interpolation: 数据插值设置项，可缺省
            interpolation: {
                // step: {number}, 用于数据插值的步长，可缺省，缺省值为 500
                // step 不宜过小，过小的 step 可能会导致绘制性能严重下降
                step: 10,
                // effectRadius: {number}, 每一个原始值在插值过程中影响的范围，可缺省，缺省值为 1000
                // effectRadius / step 的值不宜过大，建议在 20 以内，可以获得良好的性能效果
                effectRadius: 10,
            },
            // threshold: {number}, 等高线拆分步长，及按照用户提供的数据每隔 threshold 大小来绘制一条等高线
            // 可缺省，缺省值为 1
            threshold: 3,
            // smoothNumber: {number}, 等高线平滑次数，可缺省，缺省值为 2
            smoothNumber: 3,
            // style: 等高线绘制样式，可缺省
            style: {
                // height: {number}, 3D 等高线最大高度, 可缺省，缺省值为 5 * 1E4
                height: 800,
                color: ["rgba(54, 86, 205, 0.2)", "rgba(101, 95, 231, 0.2)", 'rgba(32, 194, 225, 0.2)', 'rgba(35, 213, 97, 0.2)', 'rgba(156, 213, 35, 0.2)', 'rgba(241, 226, 41, 0.2)', 'rgba(255, 191, 58, 0.2)', 'rgba(251, 141, 0, 0.2)', 'rgba(255, 82, 82, 0.2)', "rgba(188, 84, 0.2)", "rgba(255, 111, 206, 0.2)"]
                // color: ["#3656CD2e", "#655FE72e", '#20C2E12e', '#23D5612e', '#9CD5232e', '#F1E2292e', '#FFBF3A2e', '#FB8C002e', '#FF52522e', "#BC54E22e", "#FF6FCE2e"]
                // color: {Array}, 绘制等高线使用的颜色序列, 可缺省，缺省值为 ["#3656CD", "#655FE7", '#20C2E1', '#23D561', '#9CD523', '#F1E229', '#FFBF3A', '#FB8C00', '#FF5252', "#BC54E2", "#FF6FCE"]
                // color: ["rgba(7,49,117,0.1)", "rgba(4,71,138,0.1)", "rgba(0,109,176,0.1)", "rgba(6,152,196,0.1)", "rgba(65,182,196,0.1)", "rgba(127,205,187,0.2)", "rgba(199,233,180,0.2)"]
            }
        });
        
        this.contourLayer.render();
        
        // this.drawPath();
      }
        
      });
    },
    // 画轨迹线
    drawPath(){
      console.log('this.polyline', this.polyline)
      if(this.polyline!=null){
        console.log("ddd")
        this.map.remove(this.polyline);
      }
    
      this.polyline = new AMap.Polyline({
        path: this.pathData,
        isOutline: true,
        outlineColor: '#ffeeff',
        borderWeight: 1,
        strokeColor: "#3366FF",
        strokeOpacity: 1,
        strokeWeight: 5,
        // 折线样式还支持 'dashed'
        // strokeStyle: "dashed",
        // strokeStyle是dashed时有效
        strokeDasharray: [15, 5],
        showDir:true,
     	  dirColor:'pink',
        lineJoin: 'round',
        lineCap: 'round',
        zIndex: 50,
      })
      this.map.add(this.polyline);
    },

    // 获取PM2.5数值
    getInfoList(){
      listInfo(this.form).then(response => {
        console.log(response);
        this.map.remove(this.markerList);
        this.markerList = [];
        this.isTasking = response.isTasking;
        response.list.forEach(item => {
          // console.log(JSON.parse(item.areaPoint.centerpoint))
          let pm2 = item.airDataObj.allNumPm / item.airDataObj.allCountPm;
          let no2 = item.airDataObj.allNumNo2 / item.airDataObj.allCountNo2;

          var icon = new AMap.Icon({
            size: new AMap.Size(30, 30), // 图标大小
            image: require('@/images/bigscreen/point.png'), // 图标图片 URL
            imageSize: new AMap.Size(30, 30) // 图片大小
          });
          var marker = new AMap.Marker({
            position: [JSON.parse(item.areaPoint.centerpoint).lng, JSON.parse(item.areaPoint.centerpoint).lat], // 设置 Marker 的位置
            icon: icon, // 使用自定义图标
            label: {
              content: `
                <div class="custom-label">
                  <div class="label-text">${item.areaPoint.pointName}</div>
                  <div class="label-text">PM2.5: ${pm2}</div>
                  <div class="label-text">NO2: ${no2}</div>
                </div>
              `, // 嵌入图片和文字
              direction: "top", // 标签方向（top/right/bottom/left）
            }
          });

          // this.map.add(marker); 
          this.markerList.push(marker);
          /* let text = new AMap.Text({
            text: item.areaPoint.pointName + '\n' + 'PM2.5:' + pm2 + '\n' + 'NO2:' + no2,
            // anchor:'center',
            position: [JSON.parse(item.areaPoint.centerpoint).lng, JSON.parse(item.areaPoint.centerpoint).lat], // 文字位置
            style: {
                // 'padding': '.75rem 1.25rem',
                // 'margin-bottom': '1rem',
                'border-radius': '.25rem',
                'background-color': 'red',
                // 'width': '15rem',
                'border-width': 0,
                'text-align': 'center',
                'font-size': this.textFontSize+'px',
                'color': 'white' 
              }
          });
          this.map.add(text); */
          if(this.markerList.length > 0) {
            this.map.setFitView(this.markerList, true);
          }
        })
        // if(this.pm25List.length!=this.pmPolygonArr.length){
          // this.drawPmRectangleAndText();
        // }
      });
    },

    //画pm2.5的数值以及文字
    drawPmRectangleAndText(){
      this.map.remove(this.pmPolygonArr);
      this.map.remove(this.textArr);
      this.pmPolygonArr=[];
      this.textArr=[];
      this.pm25List.forEach(element => {
        var southWest = new AMap.LngLat(element.minLng, element.maxLat)
        var northEast = new AMap.LngLat(element.maxLng, element.minLat)

        var bounds = new AMap.Bounds(southWest, northEast)

        var color = this.getColor(element.messageInfo.airData[this.showDataType]);

        console.log(color)
        var rectangle = new AMap.Rectangle({
            bounds: bounds,
            strokeColor:color,
            strokeWeight: 1,
            strokeOpacity:0.5,
            strokeDasharray: [30,10],
            // strokeStyle还支持 solid
            strokeStyle: 'dashed',
            // fillColor:'rgb(0,0,0)',
            fillColor:color,
            fillOpacity:0.7,
            cursor:'pointer',
            zIndex:50,
        })

        this.pmPolygonArr.push(rectangle) ;
      });
      if(this.pmPolygonArr.length>0){
        console.log("dal")
        this.map.add(this.pmPolygonArr);
        this.map.add(this.textArr);
        // this.map.setFitView(this.pmPolygonArr);
      }
    },

    // 新增右侧数值列表展示
    getInfoListForRight() {
      this.form.fq = this.form.fqs.join(',');
      listInfo(this.form).then(response => {
        this.map.remove(this.markerList);
        this.markerList = [];
        this.isTasking = response.isTasking;
        if(this.isTasking) {
          this.getPlanePostion();
          this.timer = setInterval(() => {
            this.getPlanePostion();
          }, 20000);
        }
        response.list.forEach(item => {
          // console.log(JSON.parse(item.areaPoint.centerpoint))
          let pm2 = item.airDataObj.allNumPm / item.airDataObj.allCountPm;
          let no2 = item.airDataObj.allNumNo2 / item.airDataObj.allCountNo2;
          item.calPm2 = pm2;
          item.calNo2 = no2;
        })
        this.rightDataList = response.list;
        this.maxByPM2 = this.rightDataList.reduce((prev, current) => {
          return (prev.calPm2 > current.calPm2) ? prev.calPm2 : current.calPm2;
        });
        this.maxByNo2 = this.rightDataList.reduce((prev, current) => {
          return (prev.calNo2 > current.calNo2) ? prev.calNo2 : current.calNo2;
        });
        console.log('rightDataList', this.maxByPM2, this.maxByNo2);
        console.log('rightDataList', this.rightDataList);
      });
    },

    getRandomRGB(color){
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return 'rgb(121, 121, 21)';
      // return `rgba(${r},${g},${b}, 1)`;
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "ea203d3756bb886bcdd4833c10c332b9",
      };
      AMapLoader.load({
        key: "475db83acfc1af0cbab24fbdaa34072c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.HeatMap"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        Loca: {
          version: "1.3.2"
        }
      })
        .then((AMap) => {
          // this.defaultLayer = new AMap.createDefaultLayer()
          // this.satelliteLayer = new AMap.TileLayer.Satellite();
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            // viewMode: "3D", // 是否为3D地图模式
            // mapStyle: 'amap://styles/light',
            showLabel: false,
            // rotateEnable:true,
            // pitchEnable:true,
            zoom: 15,
            pitch: 30,
            // rotation: -15,
            viewMode:'3D', //开启3D视图,默认为关闭
            zooms:[2,20],
            layers: [new AMap.TileLayer.Satellite()],
        //     layers: [//只显示默认图层的时候，layers可以缺省
        //     new AMap.TileLayer()//高德默认标准图层
        // ],
            // center: [116.468537, 39.990434],
            center:[120.55,29.99] 
          });

          this.contourLayer = new Loca.ContourLayer({
          // shape: {string}, 等高线类型 'isoband'为等高面, 'isoline'为等高线, 必填
          shape: 'isoband',
          map: this.map
        });
          this.getAreaPoint();
      })
      .catch((e) => {
        console.log(e);
      });
    },

    getAreaPoint() {
      listPoint(this.queryParams).then(response => {
        this.pointList = response.rows;
        console.log(this.pointList);
        var area=[]
        this.pointList.forEach(item => {
          var lnglat=[];

          let basePath = JSON.parse(item.rangepoint);        
          basePath.forEach(sitem  => {
            lnglat.push([sitem.lng, sitem.lat]);
          })
          area.push({ "lnglat":[lnglat]})
        })
        console.log(area);

        var colors = ["#035594", "#117aab", "#28a2b8", "#64c4c1", "#86cfbb"];
        this.layer = new Loca.PolygonLayer({
            map: this.map,
            fitView: false
        });
        
        this.layer.setData(area, {
          lnglat: 'lnglat'
        });

        this.layer.setOptions({
          style: {
              opacity: 0.76,
              color: function (res) {
                  var index = res.index;
                  return colors[index % colors.length];
              },
              height: function () {
                  return 100;
              }
          }
        });

        this.layer.render();
      });
    },

    //地图缩放结束后的方法
    mapZoomend(){
      var zoom = this.map.getZoom();
      if(zoom<=16){
        this.textFontSize=14;
        this.drawPmRectangleAndText()
      }else if(zoom>16 && zoom<=17){
        this.textFontSize=18;
        this.drawPmRectangleAndText()
      }else if(zoom>17 && zoom<=18){
        this.textFontSize=26;
        this.drawPmRectangleAndText()
      }else if(zoom>18){
        this.textFontSize=32;
        this.drawPmRectangleAndText()
      }
      console.log("地图等级：",zoom)
    },

  },
  destroyed() {
    clearInterval(this.timer);
  }
};
</script>


<style lang="scss" scoped>
.pmInfo {
  width: 330px;
  padding: 14px 26px 14px 13px;
  border-radius: 8px;
  box-sizing: border-box;
  border: 1px solid #ebeef5;
  position: fixed;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  overflow: hidden;
  right: -400px;
  z-index: 10;
  top: 60px;
  &.fade-in {
    right: 20px;
    animation: enterFromRight 0.3s ease-in-out;
  }
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      font-weight: bold;
    }
    .el-icon-close {
      cursor: pointer;
    }
  }
  .content {
    width: 100%;
    margin-top: 10px;
    .pm-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #1a54b1;
    }
  }
}

.zbzs {
  width: 300px;
  position: absolute;
  right: 20px;
  top: 20px;
  z-index: 200;
  background-color: rgba(46, 69, 73, 0.7);
  box-sizing: border-box;
  header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 48px;
    color:#ffffff;
    overflow: hidden;
    box-sizing: border-box;
    border-bottom: 1px solid #052025;
    padding: 0px 10px;
    .titleBox {
      display: flex;
      align-items: center;
      .icon {
        margin-right: 8px;
        cursor: pointer;
      }
    }
  }
  .content {
    height: 60vh;
    .row {
      border-bottom: 1px solid #052025;
      cursor: pointer;
      .header {
        display: flex;
        align-items: center;
        height: 40px;
        color:#ffffff;
        box-sizing: border-box;
        padding: 0px 10px;
        .icon {
          width: 12px;
          margin-right: 8px;
        }
        .title {
          font-size: 14px;
        }
      }
      .data-info {
        width: 100%;
        padding: 0px 10px;
        .info-item {
          display: flex;
          align-content: center;
          justify-content: space-between;
          color: #fff;
          font-size: 14px;
          margin-bottom: 10px;
          .name {
            margin-right: 10px;
          }
          .progressBox {
            position: relative;
            width: 60%;
            height: 12px;
            border-radius: 10px;
            background-color: rgba(0, 0, 0, 0.549);
            margin-right: 10px;
            .progress {
              position: absolute;
              top: 0;
              left: 0;
              height: 100%;
              background-color: rgb(67, 101, 226);
              border-radius: 10px;
            }
            .NO2 {
              background-color: rgb(146, 216, 137);
            }
          }
        }
      }
    }
    .active {
      background-color: #5b94f03f;
    }
  }
}

.pmsz {
  width: 300px;
  position: absolute;
  right: 340px;
  top: 20px;
  z-index: 200;
  background-color: #179bb2b3;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #fff;
  height: 48px;
  color: #ffffff;
  box-sizing: border-box;
  padding: 0px 10px;
}

@keyframes enterFromRight {
  from {
    right: -400px;
  }
  to {
    right: 0;
  }
}
</style>
<style>
 #container{
        padding:0px;
        margin: 0px;
        width: 100%;
        height: 100vh;
  }
.amap-icon img {
  width: 25px;
  height: 34px;
}
.custom-label {
  background: url("~@/images/bigscreen/text-bg.png") no-repeat;
  background-size: 100% 100%;
  color: #fff;
  padding: 12px 18px;
}
.label-text {
  margin-bottom: 5px;
}
.mapspec .amap-marker-label {
  background-color: transparent;
  border: none;
  padding: 0;
}

.el-scrollbar__wrap {
  overflow-x: hidden !important;;
}
</style>